package Network

import (
	"fmt"
	"net"
)

type Server struct {
	// ip & port
	IP   string
	Port int

	// Listener
	listen net.Listener

	// Close Channel
	closeChan chan int

	// All Client
	allClients map[int]Client
}

func NewServer(port int) Server {

	var server Server

	server.IP = "localhost"
	server.Port = port
	server.closeChan = make(chan int)
	server.allClients = make(map[int]Client)

	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		panic(err)
	}
	server.listen = lis

	return server
}

// Notify server shutdown
func (server Server) Stop() {
	// server.closeChan <- 1
	server.listen.Close()
}

// Send string to client
func (server Server) SendString(id int, str string) {
	client, ok := server.allClients[id]
	if ok {
		fmt.Fprint(client.Conn, str)
	}
}

// Start receive connection
func (server Server) Start(handle func(Client)) {

	var clientIndex int = 0

	// Register shutdown function
	/*
		go func(){
			for {
				select {
				case <- server.closeChan:
					fmt.Println("It will shutdown.")
				}
			}
		}()*/

	for {
		var client Client
		client.ID = clientIndex

		conn, err := server.listen.Accept()
		if err != nil {
			panic(err)
		}
		client.Conn = conn
		client.closeChan = make(chan int)

		// Save a Client
		server.allClients[clientIndex] = client

		// Create goroutine to invoke handle connection
		go handle(client)

		// Increment client index.
		clientIndex++
	}
}
